/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <cerrno>
#include <cstdlib>
#include <limits>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    int dfs(TreeNode*root)
    {
        if(root==nullptr) return 0;
        if(root->left==nullptr&&root->right==nullptr)  return 1;
        int left=dfs(root->left);
        int right=dfs(root->right);
        return max(left,right)+1;

    }
    bool IsBalanced_Solution(TreeNode* pRoot) 
    {
        if(pRoot==nullptr) return true;
        int left=dfs(pRoot->left);
        int right=dfs(pRoot->right);
        if(abs(right-left)>1) return false;
    

        return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
     }
};

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <cerrno>
#include <cstdlib>
#include <limits>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    int dfs(TreeNode*root)
    {
        if(root==nullptr) return 0;
        if(root->left==nullptr&&root->right==nullptr)  return 1;
        int left=dfs(root->left);
        int right=dfs(root->right);
        if(left==-1||right==-1) return -1;
        if(abs(right-left)>1) return -1;
        return max(left,right)+1;

    }
    bool IsBalanced_Solution(TreeNode* pRoot) 
    {
       return dfs(pRoot)!=-1;
    }
};